package com.baoxin.chenxixc4coach;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;

import org.json.JSONObject;

public class LoginActivity extends BaseActivity {

    private EditText mPhone;
    private EditText mPassWord;
    private View mProgressView;
    private View mLoginFormView;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) toolbar.getLayoutParams();
        lp.topMargin = getStatusBarHeight();
        toolbar.setLayoutParams(lp);
        //在setSupportActionBar之后才有效
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                if (!MainActivity.isRun) {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
        });

        Button signInButton = findViewById(R.id.login_bt);
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mPhone = findViewById(R.id.phone_et);
        mPassWord = findViewById(R.id.password_et);
        mProgressView = findViewById(R.id.login_progress);
        mLoginFormView = findViewById(R.id.login_form);

    }

    @Override
    protected void onStart() {
        uiOpions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        super.onStart();

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                Bundle bundle = msg.getData();
                String tip = bundle.getString("msg");
                switch (msg.what) {
                    case Msg.ONFAILURE:
                        showProgress(false);
                        break;
                    case Msg.LOGIN_SUCCEED:
                        Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                        MyApplication.saveUser(phone, password);
                        if (MainActivity.isRun) {//说明是从其他地方进去的，登陆成功后直接finish就行了
                            setResult(Msg.LOGIN_SUCCEED);
                        } else {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                        finish();
                        break;
                    case Msg.LOGIN_FAILED:
                        Toast.makeText(LoginActivity.this, tip, Toast.LENGTH_SHORT).show();
                        showProgress(false);
                        break;
                }
            }
        };
    }

    String phone = "";
    String password = "";

    /**
     * 点击登录
     */
    private void attemptLogin() {

        phone = mPhone.getText().toString();
        password = mPassWord.getText().toString();

        // Check for a valid password, if the user entered one.
        if (!isPasswordValid(password)) {
            mPassWord.setError("密码过短！");
            return;
        }

        // Check for a valid email address.
        if (phone.length() != 11) {
            mPhone.setError("手机格式错误！");
        }

        showProgress(true);

        login(phone, password);


    }

    public void switchToRegister(View view) {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    private boolean isPasswordValid(String password) {
        return password.length() >= 6;
    }

    private void showProgress(final boolean show) {

        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });

    }

    private void login(String userName, String password) {
        JSONObject body = new JSONObject();
        try {
            body.put("phone", userName);
            body.put("password", password);
            body.put("type", 0);
            NetUtil.post(this, Interfaces.URL_LOGIN_IN, body.toString(),
                    new MyCallback(Interfaces.URL_LOGIN_IN, handler));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSkip(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
